﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using WebLog;

namespace VotanetWebSite.Home
{
    public partial class Pagina_Inicio : System.Web.UI.Page
    {

        protected readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        protected readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        protected readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        protected readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();

        private Voter GetVoter()
        {
            return Session["Voter"] as Voter;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Uri previousPage = HttpContext.Current.Request.UrlReferrer;

                if (GetVoter() != null && previousPage != null && previousPage.AbsolutePath == "/Login_Votante.aspx")
                {
                    LoadVotingGrid(KEY, (GetVoter().id));
                    LoadVoucherGrid((GetVoter().id));
                    LoadVoter(GetVoter());
                    LoadRegisterGrid((GetVoter().id));
                }
                else
                {
                    Response.RedirectPermanent("~/Login_Votante.aspx");
                }
            }

        }

        private void LoadRegisterGrid(string id)
        {
            List<string> register = new VoterLogic().GetListVoterRegisterLogic(id);
            if (register != null)
            {
                GrillaLogin.DataSource = register;
                GrillaLogin.DataBind();
            }

        }


        private void LoadVoucherGrid(string id)
        {
            List<VoucherVoting> list = new VotingLogic().GetListVoucherVotingLogic(id, KEY);
            if (list != null)
            {
                GrillaComprobante.DataSource = list;
                GrillaComprobante.DataBind();
                GrillaComprobante.Visible = true;
                GrillaComprobante.Enabled = true;
            }

        }

        private void LoadVotingGrid(string KEY, string id)
        {
            List<Voting> list = new VotingLogic().GetListVotingOfVotersLogic(KEY, id);
            if (list != null)
            {
                GrillaVotaciones.DataSource = list;
                GrillaVotaciones.DataBind();
            }
            else
            {
                GrillaVotaciones.Visible = false;
                GrillaVotaciones.Enabled = false;
                lblmensaje.Visible = true;
                lblmensaje.Enabled = true;
            }
        }

        private void LoadVoter(Voter voter)
        {
            lblNombreVotanteLogin.Text = voter.GetFullName();
            lblNomreVotante.Text = voter.GetFullName();
            lblRut.Text = voter.rut;
            lblEmail.Text = voter.email;
            lblDireccion.Text = voter.address;
            lblcelular.Text = voter.cellPhone;
            lbltelefono.Text = voter.telephone;
            lblFechaNacimiento.Text = voter.registrationDate.ToShortDateString();
            if (string.IsNullOrWhiteSpace(voter.picturePath))
            {
                VoterPicture.ImageUrl = "~/Images/no_disponible.jpg";
                //LoadAddUserPictureMenu(true);
            }
            else
            {
                VoterPicture.ImageUrl = "~/Images/VoterPicture/" + voter.picturePath;
            }
        }

        //private void LoadAddUserPictureMenu(bool p)
        //{

        //    btnGuardarFoto.Visible = p;
        //    btnGuardarFoto.Enabled = p;
        //    RFVFUVoterPicture.Visible = p;
        //    RFVFUVoterPicture.Enabled = p;
        //    REFUVoterPicture.Visible = p;
        //    REFUVoterPicture.Enabled = p;
        //    vceRFVFUVoterPicture.Enabled = p;
        //    vceREFUVoterPicture.Enabled = p;
        //    FUVoterPicture.Visible = p;
        //    FUVoterPicture.Enabled = p;
        //}




        protected void btnGuardarFoto_Click(object sender, EventArgs e)
        {
             FileUpload fileUpload = FUVoterPicture;
            Voter voter = GetVoter();
            if (voter != null)
            {
                string oldPicture = voter.picturePath;
                voter.picturePath = GetPictureName(fileUpload, voter.name + voter.lastName + voter.secondLastName);
                voter.voterPicture = FUVoterPicture;
                VoterLogic vl = new VoterLogic();

                bool respuesta = vl.UpgradeVoterPictureLogic(voter);

                if (respuesta)
                {
                    Bitmap imagenModificada = CustomizeControl.ResizePicture(FUVoterPicture);
                    string urlFotografia = HttpContext.Current.Server.MapPath("~/Images/VoterPicture/");

                    try
                    {
                        if (!File.Exists(urlFotografia + voter.picturePath))
                        {
                            File.Delete(urlFotografia + oldPicture);
                            imagenModificada.Save(urlFotografia + voter.picturePath);
                        }
                        else
                        {
                            File.Delete(urlFotografia + oldPicture);
                            imagenModificada.Save(urlFotografia + voter.picturePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger logger = Logger.GetInstance;
                        logger.WriteLog(ex);
                        Messages.Show(Page, Messages.NO_PICTURE_ENTRY);
                    }

                    VoterPicture.ImageUrl = "~/Images/VoterPicture/" + voter.picturePath;

                    Messages.Show(Page, Messages.PICTURE_ENTRY);
                }
                else
                {
                    Messages.Show(Page, Messages.NO_PICTURE_ENTRY);
                }
            }

        }

        protected string GetPictureName(FileUpload hpf, string pictureString)
        {
            string[] extension = hpf.FileName.Split('.');

            string picture = "Imagen" + pictureString + "(" + extension[0] + ")." + extension[1];
            return picture;
        }

        protected void GrillaVotaciones_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "votoVotante":
                    string idVotacion = e.CommandArgument.ToString();
                    Context.Items.Add("Vota_Id", idVotacion);
                    Server.Transfer("~/Acceso_Votante/Sufragio_Votante.aspx");
                    break;
            }
        }

        protected void GrillaComprobante_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "votoVotante":
                    string path = HttpContext.Current.Server.MapPath(e.CommandArgument.ToString());
                    Response.ContentType = "Application/pdf";
                    Response.WriteFile(path);
                    Response.End();
                    break;
            }
        }

        protected void btnSavePass_Click(object sender, EventArgs e)
        {
            string oldPassword = txtOldPass.Text;
            string newPassword = txtnewPass.Text;
            string newPasswordRepet = txtnewPassRepet.Text;

            string response = new VoterLogic().UpdateVoterPasswordLogic(GetVoter(), oldPassword, newPassword, newPasswordRepet, KEY, MAIL_SERVER, USER_PASSWORD, USER_MAIL);
            CleanForm();
            Messages.Show(Page, response);

        }

        protected void btnCancelPass_Click(object sender, EventArgs e)
        {
            CleanForm();
        }

        protected void CleanForm()
        {
            txtOldPass.Text = string.Empty;
            txtnewPass.Text = string.Empty;
            txtnewPassRepet.Text = string.Empty;
        }

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }
    }
}